from flask import json


from tools.Db import get_db_connection
from tools.Func import format_time
from tools.Result import is_success


def add_log(pro_type, title, url,result):
    """添加新用户到数据库"""
    conn = get_db_connection()
    result_res=1 if is_success(result) else 0
    time=format_time()
    try:
        with conn.cursor() as cursor:
            # 使用参数化查询防止 SQL 注入
            sql = """
            INSERT INTO logs 
            (type, title, url, result_res,result_msg, add_time) 
            VALUES (%s, %s, %s,%s,%s,%s)
            """
            # 执行 SQL 并传入参数
            cursor.execute(sql, (pro_type, title, url,result_res,json.dumps(result, ensure_ascii=False, indent=2), time))

            # 获取新插入记录的 ID


        # 提交事务（重要！）
        conn.commit()

        # 返回新记录的 ID
        return True

    except Exception as e:
        # 发生异常时回滚事务
        conn.rollback()

        raise  # 重新抛出异常以便上层处理

    finally:
        # 确保连接关闭
        conn.close()


def get_logs_for_page(page: int, page_size: int,
                      startTime=None, endTime=None,
                      result_res=None,proType=None):
    print(result_res)
    conn = get_db_connection()
    try:
        with conn.cursor() as cursor:
            # 构建查询条件
            conditions = []
            params = []

            # 时间范围条件
            if startTime and endTime:
                conditions.append("(add_time BETWEEN %s AND %s)")
                params.extend([startTime, endTime])
            elif startTime:
                conditions.append("add_time >= %s")
                params.append(startTime)
            elif endTime:
                conditions.append("add_time <= %s")
                params.append(endTime)

            # 结果状态条件
            if result_res is not None:
                conditions.append("result_res = %s")
                params.append(result_res)

            if proType is not None:
                conditions.append("type = %s")
                params.append(proType)
            # 构建完整WHERE子句
            where_clause = " AND ".join(conditions) if conditions else ""

            # 查询总记录数（带条件）
            count_sql = f"""
                SELECT COUNT(*) AS total 
                FROM logs 
                {where_clause and 'WHERE ' + where_clause}
            """
            cursor.execute(count_sql, params)
            total = cursor.fetchone()["total"]

            # 计算分页参数
            offset = (page - 1) * page_size

            # 分页查询（带条件）
            data_sql = f"""
                SELECT 
                    id, type, title, url, 
                    result_res, result_msg, add_time 
                FROM logs
                {where_clause and 'WHERE ' + where_clause}
                ORDER BY add_time DESC
                LIMIT %s OFFSET %s
            """
            cursor.execute(data_sql, params + [page_size, offset])
            data = cursor.fetchall()
            print(data)

            return total, data

    except Exception as e:
        conn.rollback()

        raise
    finally:
        conn.close()